package com.gujia.rabbitmq.simple;

import com.gujia.rabbitmq.util.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费者获取消息
 */
public class SimpleConsumers {
    private static final String QUEUE_NAME="test_simple_queue";
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //获取连接
        Connection connection =  ConnectionUtils.getConnction();
        //创建频道
        Channel channel = connection.createChannel();
        //声明队列
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);

        DefaultConsumer consumer = new DefaultConsumer(channel) {
             @Override
             public void handleDelivery(String consumerTag, Envelope envelope,
                                        AMQP.BasicProperties properties, byte[] body) throws IOException {
                 String msgString = new String(body,"utf-8");
                 System.out.println("new api recv:"+msgString);
             }
         };
        //监听队列
        channel.basicConsume(QUEUE_NAME,true,consumer);
    }

    private static void oldApi() throws IOException, TimeoutException, InterruptedException{
        //获取连接
        Connection connection =  ConnectionUtils.getConnction();
        //创建频道
        Channel channel = connection.createChannel();

        //老版本：
        //定义队列的消费者
        QueueingConsumer queueingConsumer =  new QueueingConsumer(channel);

        //监听队列的消费者：
        channel.basicConsume(QUEUE_NAME,true,queueingConsumer);

        while (true){
            QueueingConsumer.Delivery delivery= queueingConsumer.nextDelivery();

            String msgString = new String(delivery.getBody());
            System.out.println("[SimpleConsumers] msg :"+msgString);
        }

    }
}
